package com.ruyuan.seckilling.render.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.ruyuan.seckilling.render.entity.PageConfig;
import com.ruyuan.seckilling.render.mapper.PageConfigMapper;
import com.ruyuan.seckilling.render.service.PageConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author zhonghuashishan
 */
@Service
public class PageConfigServiceImpl implements PageConfigService {

    private final Cache<String, PageConfig> cache = CacheBuilder.newBuilder()
            .maximumSize(100)
            .expireAfterWrite(30, TimeUnit.MINUTES)
            .build();

    @Autowired
    private PageConfigMapper pageConfigMapper;

    @Override
    public PageConfig queryByPageCode(String pageCode) {
        try {
            return cache.get(pageCode, () -> {
                QueryWrapper<PageConfig> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("page_code", pageCode);
                return pageConfigMapper.selectOne(queryWrapper);
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void save(PageConfig pageConfig) {
        pageConfigMapper.insert(pageConfig);
    }

    @Override
    public void removeByPageCode(String pageCode) {
        try {
            QueryWrapper<PageConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("page_code", pageCode);
            pageConfigMapper.delete(queryWrapper);
        } finally {
            cache.invalidate(pageCode);
        }
    }
}
